package com.powernode.controller;

import cn.hutool.captcha.LineCaptcha;
import com.powernode.common.Constants;
import com.powernode.domain.SysUser;
import com.powernode.service.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 描述：
 * 作者：动力节点·武汉
 */
@Controller
@RequestMapping("login")
public class LoginController {

    @Resource
    private SysUserService userService;

    /**
     * 跳转到登陆 页面
     */
    @GetMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 完成登陆操作
     */
    @PostMapping("doLogin")
    public String doLogin(Model model, String username, String password, String  code, HttpSession session){
        //判断验证码
        LineCaptcha lineCaptcha= (LineCaptcha) session.getAttribute(Constants.CAPTCHA_CODE_KEY);
        if(!lineCaptcha.verify(code)){
            model.addAttribute("error","验证码不正确");
            return "login";
        }else{
            SysUser user=userService.login(username,password);
            if(null!=user){
                user.setPassword("");
                session.setAttribute(Constants.SESSION_USER_KEY,user);
                return "redirect:/page/index";
            }else{
                model.addAttribute("error","用户名或密码不正确");
                return "login";
            }
        }
    }

}
